module Main where
import Control.Concurrent
import System.IO 
import Data.Time.Clock
import System.Environment
import System.Process
import Data.IORef
import Control.Monad
import qualified Data.Text as T
import qualified Data.Text.Read as TR
import qualified Data.Text.IO as TI

-- import Codec.FFmpeg
difftimtofloat:: DiffTime->Float
difftimtofloat a=realToFrac a 

inttofloat:: Int->Float
inttofloat a=realToFrac a 



sleepMs::Int -> IO ()
sleepMs n=threadDelay (n*1000000)


mytask::(Int,String,String)->IO ()
mytask (inter, execute_path,pro_path)= do 
    a<-newIORef 0
    b<-return.difftimtofloat=<<myget_curdaytime
    forever $ do 
        c<-return.difftimtofloat=<< myget_curdaytime
        aa<-readIORef a
        if (c-b)>aa*(inttofloat inter) then do 
            putStrLn $ "execute" ++ pro_path  
           -- system pro_path

            (_,_,_,ph)<-createProcess (shell ("cd " ++ execute_path ++ "&& " ++ pro_path))
            waitForProcess ph
            -- callCommand ".\\test2"
            modifyIORef a (\x->x+1)
        else
            return ()
        -- putStrLn $ "once " ++ (show aa)
        sleepMs 1
    putStrLn "mytask"



myget_curtime:: IO UTCTime
myget_curtime = do 
    a<- getCurrentTime
    return $ addUTCTime (60*60*8) a
myget_curdaytime::IO DiffTime
myget_curdaytime= return.utctDayTime=<<myget_curtime


main :: IO ()
main = do 
    let 
        myfun::Either String (Int,T.Text)->String->String->IO ()
        myfun (Left y) _ _ = return ()
        myfun (Right (a,_)) s s1= mytask (a,s,s1) 
        myfun1::[String]->IO () 
        myfun1 s= if Prelude.length s==3 
            then do
                h<-openFile "task_config.txt" WriteMode
                hPutStr h $ "interval= " ++ (s!!0) ++ "\n"
                hPutStr h $ "execute_dir= " ++ (s!!2) ++ "\n" 
                hPutStr h $ "program_path= " ++ (s!!1) ++ "\n"
                hClose h 
                myfun (TR.decimal (T.pack (s!!0))) (s!!1) (s!!2)

            else do
                h<-openFile "task_config.txt" ReadMode
                l<-TI.hGetLine h 
                inter<-return$ TR.decimal ((T.words l)!!1)
                putStrLn $show inter
                l<-TI.hGetLine h 

                execute_path<- return$ T.unpack ((T.words l) !! 1)
                putStrLn execute_path 

                l<-TI.hGetLine h 
                path<-return $ T.unpack ((T.words l)!!1)
                putStrLn path
                hClose h 
                myfun inter  execute_path path
                
    putStrLn "begin "
    args<- getArgs 
    putStrLn $ show args
     

    -- putStrLn . show =<< myget_curdaytime
     
    -- putStrLn $show $ TR.double (T.pack "12.4")
    -- threadDelay 5000000
    -- putStrLn . show =<< myget_curdaytime

    -- putStrLn .show .difftimtofloat=<<myget_curdaytime 
    myfun1 args
    putStrLn "Hello, Haskell!"
